﻿using System.Collections.Generic;
using System.Linq;
using MvcDesign.Core.CoreServices;
using MvcDesign.Core.CoreViewModel;
using MvcDesign.Core.DataAccess;

namespace MvcDesign.Forum.ForumServices
{
    class ForumPathViewService : IForumPathViewService
    {
        private readonly IPathViewService _pathViewService;

        public ForumPathViewService(IPathViewService service)
        {
            _pathViewService = service;
        }

        public Path GetPathRoot()
        {
            return _pathViewService.GetPathRoot();
        }

        public TopTab GetTopTabs()
        {
            return _pathViewService.GetTopTabs();
        }

        private Path GetPathSection(ForumDataModel.Section section, bool isCurrent)
        {
            return new Path
            {
                Name = section.Name,
                Url = isCurrent ? null : MvcHelper.UrlHelper.RouteUrl(new { controller = "Forum", action = "Section", id = section.Id })
            };
        }


        private void GetFullPathSection(DataContext domainModel, ForumDataModel.Section section, List<Path> path)
        {
            section = domainModel.GetCollection<ForumDataModel.Section>().FirstOrDefault(s => s.Id == section.ParentSectionId);

            if (section == null)
            {
                return;
            }

            path.Insert(0, GetPathSection(section, false));

            GetFullPathSection(domainModel, section, path);
        }


        public List<Path> GetFullPathSection(long sectionId, bool isCurrent)
        {
            using (var domainModel = new DataContext())
            {
                var section = domainModel.GetCollection<ForumDataModel.Section>().Find(sectionId);
                var ret = new List<Path> { GetPathSection(section, isCurrent) };
                GetFullPathSection(domainModel, section, ret);
                ret.Insert(0, GetPathSections());
                return ret;
            }
        }

        public List<Path> GetFullPathThread(long threadId)
        {
            ForumDataModel.Thread thread;

            using (var domainModel = new DataContext())
            {
                thread = domainModel.GetCollection<ForumDataModel.Thread>().Find(threadId);
            }

            var ret = new List<Path>();
            ret.AddRange(GetFullPathSection(thread.SectionId, false));
            ret.Add(new Path { Name = thread.Name });
            return ret;
        }

        public Path GetPathSections()
        {
            return new Path { Name = "Sections" };
        }
    }
}
